import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wch/constant/event_bus_global.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/flags_widget.dart';
import 'package:wch/model/report_list_entity.dart';
import 'package:wch/page/data_stage.dart';
import 'package:wch/page/eeg_list.dart';
import 'package:wch/page/pdf_provider.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/time_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../main.dart';
import '../model/acquisition_entity.dart';
import '../model/flag_model.dart';
import '../model/patient_label.dart';
import '../native/net_business.dart';
import '../utils/color_utils.dart';
import '../utils/log_utils.dart';

class DataReportPage extends StatefulWidget {
  DataReportPage({super.key,  this.searchWords, this.sickPersonId});

  String? searchWords;
  final int? sickPersonId;

  @override
  State<DataReportPage> createState() => _DataReportPageState();
}

class _DataReportPageState extends State<DataReportPage> with AutomaticKeepAliveClientMixin, RouteAware, TickerProviderStateMixin{
  //睡眠时长
  // int sleepDuration = 200;

  // //报告已生成
  // bool isCreatedReport = false;
  //
  // //是否已分期
  // bool isStaged = false;

  //是否有标签
  bool showFlag = false;
  
  // List<Widget> models = [];
  
  // double flagsHeight = 0;

  ReportListEntity entity = ReportListEntity();

  ///页码
  int page = 1;
  bool noMoreData = false;
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  final ScrollController _scrollController = ScrollController(keepScrollOffset: true);

  OverlayEntry? entry;
  @override
  bool get wantKeepAlive => true;

  StreamSubscription? searchWordsSubscription;

  PatientLabelModel? patientLabelModel;

  AnimationController? animationController;
  Animation<double>? animation;

  ///是否显示加载中，当进入数据分期页面，再返回时，由于横竖屏切换，会导致控件越界，因此，加一个标识
  bool isPop = false;
  ///偏移值
  double scrollOffsetY = 0;

  @override
  void didChangeDependencies() {
    routeObserver.subscribe(
        this, ModalRoute.of(context) as PageRoute);
    super.didChangeDependencies();
  }

  @override
  void didPopNext() {
    super.didPop();
    if (isPop) {
      setState(() {
        isPop;
      });
      Timer(Duration(seconds: 1), (){
        setState(() {
          isPop = false;
          _onRefreshCurPage();
        });
      });
    }
  }

  @override
  void didPush() {
    super.didPush();
    LogUtils.log('didPush');
  }
  @override
  void didPushNext() {
    super.didPushNext();
    LogUtils.log('didPushNext');
  }

  @override
  void dispose() {
    searchWordsSubscription?.cancel();
    animationController?.dispose();
    super.dispose();
  }

  @override
  void initState() {
    if (entity.data == null) {
      entity.data = ReportListData();
      entity.data?.data ??= [];
    }

    NetBusiness().reportList(page, widget.searchWords, widget.sickPersonId).then((value){
      setState(() {
        entity = value;
      });
    });

    searchWordsSubscription = globalEventBus.on<SearchWords>().listen((value){
      widget.searchWords = value.words;
      _onRefresh();
    });

    NetBusiness().hospitalConfig().then((onValue){
      setState(() {
        if (onValue.data?.isLabelConfig == 'Y') {
          showFlag = true;
        }
      });
    });

    NetBusiness().patientAllLabel(0).then((value){
      patientLabelModel = value;
    });

    /// 动画持续时间是 3秒，此处的this指 TickerProviderStateMixin
    animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )
      ..repeat();
    animation = Tween<double>(begin: 1, end: 0).animate(animationController!);

    _scrollController.addListener((){
      scrollOffsetY = _scrollController.offset;
    });
  }

  void _onRefresh() async{
    // monitor network fetch
    page = 1;
    NetBusiness().reportList(page, widget.searchWords, widget.sickPersonId).then((value) {
      entity = value;
      if (value.data!.data!.length < 10) {
        noMoreData = true;
      } else {
        noMoreData = false;
        _refreshController.resetNoData();
      }
      setState(() {
        entity;
      });
      _refreshController.refreshCompleted();
    });
  }

  void _onLoading() async{
    if (noMoreData) {
      _refreshController.loadNoData();
      return;
    }
    page ++;
    NetBusiness().reportList(page, widget.searchWords, widget.sickPersonId).then((value) {
      if (entity.data == null) {
        entity = value;
      } else {
        entity.data!.data!.addAll(value.data!.data!);
      }
      if (value.data!.data!.length < 10) {
        noMoreData = true;
      }
      setState(() {
        entity;
      });
      _refreshController.loadComplete();
    });
  }
  ///刷新到当前页
  void _onRefreshCurPage() async{
    if (noMoreData) {
      _refreshController.loadNoData();
      return;
    }
    NetBusiness().reportList(1, widget.searchWords, widget.sickPersonId, page*10).then((value) {
      if (entity.data == null) {
        entity = value;
      } else {
        entity.data!.data!.clear();
        entity.data!.data!.addAll(value.data!.data!);
      }
      if (value.data!.data!.length < 10) {
        noMoreData = true;
      }
      setState(() {
        entity;
      });
      _refreshController.loadComplete();
      _scrollController.animateTo(scrollOffsetY, duration: Duration(milliseconds: 10), curve: Curves.bounceIn);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Color(0xFFF8F9FB),
      child: isPop ? buildRotationTransition() : entity.data!.data!.isNotEmpty ?
      SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        footer: CustomFooter(
          builder: (context,mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        header: CustomHeader(builder: (context, mode) {
          Widget body = Container();
          if(mode==RefreshStatus.idle){
            body =  Text("下拉刷新");
          }
          else if(mode==RefreshStatus.refreshing){
            body =  CupertinoActivityIndicator();
          }
          else if(mode == RefreshStatus.failed){
            body = Text("刷新失败！请稍后重试！");
          }
          else if(mode == RefreshStatus.canRefresh){
            body = Text("松手,立即刷新!");
          }
          else if(mode == RefreshStatus.completed){
            body = Text("刷新完成!");
          }
          return Container(
            height: 55.0,
            child: Center(child:body),
          );
        },
        ),
        child: ListView.separated(
            controller: _scrollController,
            itemBuilder: (ctx, index) {
              return _getItem(index);
            },
            separatorBuilder: (ctx, index) {
              return Divider(
                height: 10,
                thickness: 10,
                color: Colors.transparent,
              );
            },
            itemCount: entity.data!.data!.length),
      ) : Container(
            height: 100.h,
            child: Column(
              children: [
                VerPadding(100.h),
                Image.asset(
                  searchEmptyPng,
                  width: 71.w,
                  height: 52.h,
                ),
                VerPadding(15.h),
                F12TitleText(widget.searchWords == null || widget.searchWords!.isEmpty ?'暂无数据报告' : '没有“${widget.searchWords}”相关内容',
                    color: contentTextColor),
              ],
            ),
          ),
    );
  }

  String showName(String? name){
    if (name == null || name.isEmpty) return '';
    if (name.length > 4)  return '${name.substring(0, 4)}...';
    return name;
  }

  //旋转
  Widget buildRotationTransition() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          RotationTransition(
            //设置动画的旋转中心
            alignment: Alignment.center,
            //动画控制器
            turns: animation!,
            //将要执行动画的子view
            child: Image.asset(searchLoadingIcon, width: 40, height: 40,),
          ),
          VerPadding(14.h),
          const F14TitleText('睡眠报告加载中...', color: Color(0xFF515151)),
        ],
      ),
    );
  }

  Widget _getItem(int id) {
    double flagsHeight = 0;
    List<FlagModel> labels = [];
    if (entity.data!.data![id].labelList != null) {
      for (int i = 0; i < entity.data!.data![id].labelList!.length; i++) {
        AcquisitionAcquisitionLabelList label = entity.data!.data![id].labelList![i];
        Color color = ColorUtils.getColorFromHex(label.colour!);
        labels
            .add(FlagModel(label.name!, false, color.withOpacity(0.2), color));
      }
    }
    List<Widget> models = FlagsWidget.getFlagsWidget2(labels, ScreenUtil().screenWidth-130.w, 60, 10, (widgetHeight){
      flagsHeight = widgetHeight;
    });
    List<Widget> widgets = _getButtonWidgets(id);
    return Container(
      padding: EdgeInsets.fromLTRB(20.w, 15.h, 20.w, 0),
      height: flagsHeight + 141.h + (entity.data!.data![id].btnCount! > 0 ? 35.h : 0),
      width: ScreenUtil().screenWidth - 30.w,
      margin: EdgeInsets.symmetric(horizontal: 15.w),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(7.5.h))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          F15TitleText('采集编号：${entity.data!.data![id].id}', color: Color(0xFF424242)),
          VerPadding(15.h),
          LineWidget(width: ScreenUtil().screenWidth - 70.w, height: 1.h, color: const Color(0xFFF8F9FB),),
          VerPadding(10.h),
          Row(
            children: [
              Image.asset(
                reportIcon,
                width: 50.w,
                height: 50.w,
              ),
              HorPadding(12.w),
              Expanded(
                child: Column(
                  children: [
                    Row(
                      children: [
                        F13TitleText(showName(entity.data!.data![id].userName),
                            color: F2TextColor),
                        HorPadding(8.w),
                        Image.asset(
                          entity.data!.data![id].sex == '男' ? hospitalMaleIcon : hospitalFemaleIcon,
                          width: 9.w,
                          height: 13.5.h,
                        ),
                        HorPadding(25.w),
                        F13TitleText(
                          '${entity.data!.data![id].age ?? 0}岁',
                          color: F2TextColor,
                        ),
                        HorPadding(16.w),
                        F13TitleText(entity.data!.data![id].mobile ?? '', color: F2TextColor),
                      ],
                    ),
                    VerPadding(5.h),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        F13TitleText('${splitTime(entity.data!.data![id].startTime, 0)}', color: F2TextColor),
                        F13TitleText('${splitTime(entity.data!.data![id].startTime, 1)}', color: F2TextColor),
                        Visibility(maintainSize: true, maintainAnimation:true, maintainState:true, visible: entity.data!.data![id].duration != null && entity.data!.data![id].duration! != 3, child: F13TitleText(TimeUtils.second2ChinaHHmmss(entity.data!.data![id].duration ?? 0), color: F2TextColor)),
                      ],
                    ),
                    VerPadding(10.h),
                    Container(
                      width: ScreenUtil().screenWidth-130.w,
                      height: flagsHeight,
                      child: Stack(
                        children: models,
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
          VerPadding(5.h),
          Column(
            children: [
              VerPadding(5.h),
              LineWidget(width: ScreenUtil().screenWidth - 70.w, height: 1.h, color: const Color(0xFFF8F9FB),),
              VerPadding(5.h),
              Row(
                children: widgets,
              )
            ],
          )
        ],
      ),
    );
  }

  String splitTime(String? time, int index) {
    if (time == null) {
      return '';
    }
    return time.split(' ')[index];
  }

  List<Widget> _getButtonWidgets(int id) {
    List<Widget> widgets = [];
    List<String> btns = [];
    int duration = entity.data!.data![id].duration ?? 0;
    String status = entity.data!.data![id].status ?? '';
    String stageStatus = entity.data!.data![id].stageStatus ?? '';
    String stageDataStatus = entity.data!.data![id].stageDataStatus ?? '';
    bool hasFlag = entity.data!.data![id].labelList != null && entity.data!.data![id].labelList!.isNotEmpty;

    int buttonsCount = 0;
    // if (stageDataStatus == 'Y' && duration >= 300) {
    //   if (stageStatus == 'N' && status != 'FINISH') {///
    //     buttonsCount += 1;
    //   }
    //   else if (stageStatus == 'Y' && status != 'FINISH') {
    //     buttonsCount += 1;
    //   }
    //   else if (stageStatus == 'Y' && status == 'FINISH') {
    //     buttonsCount += 2;
    //   }
    // }
    
    if (status == 'FINISH') {
      buttonsCount += 2;//已分期，已生成
      btns.add('查看报告');
      btns.add('重新分期');
    } else {
      if (stageDataStatus == 'Y' && duration >= 300 && stageStatus == 'Y') {
        buttonsCount += 1;//已分期，未生成
        btns.add('重新分期');
      } else if (stageDataStatus == 'Y' && duration >= 300 && stageStatus == "N") {
        buttonsCount += 1;//未分期，未生成
        btns.add('开始分期');
      }
    }

    if (showFlag && hasFlag) {
      buttonsCount += 1;
      btns.add('修改标签');
    }

    double btnWidth = 0;
    if (buttonsCount > 0) {
      btnWidth = (ScreenUtil().screenWidth - 70.w - (buttonsCount > 1 ? (buttonsCount - 1) * 0.5 : 0)) / buttonsCount - (btns.length-1)*0.5;
    }

    // if (buttonsCount == 1) {
    //   if (hasFlags) {
    //     widgets.add(lookReport('修改标签', themeColor, btnWidth, id));
    //   } else {
    //     if (stageStatus == 'Y') {
    //       widgets.add(lookReport('重新分期', themeColor, btnWidth, id));
    //     } else {
    //       widgets.add(lookReport('开始分期', themeColor, btnWidth, id));
    //     }
    //   }
    //
    // } else if (buttonsCount == 2) {
    //   if (hasFlags) {
    //     if (stageStatus == 'Y') {
    //       widgets.add(lookReport('重新分期', themeColor, btnWidth, id));
    //     } else {
    //       widgets.add(lookReport('开始分期', themeColor, btnWidth, id));
    //     }
    //     widgets.add(LineWidget(width: 0.5, height: 45.h));
    //     widgets.add(lookReport('修改标签', themeColor, btnWidth, id));
    //   } else {
    //     widgets.add(lookReport('查看报告', F2TextColor, btnWidth, id));
    //     widgets.add(LineWidget(width: 0.5, height: 45.h));
    //     widgets.add(lookReport('重新分期', themeColor, btnWidth, id));
    //   }
    // } else if (buttonsCount == 3){
    //   widgets.add(lookReport('查看报告', F2TextColor, btnWidth, id));
    //   widgets.add(LineWidget(width: 0.5, height: 45.h));
    //   widgets.add(lookReport('重新分期', themeColor, btnWidth, id));
    //   widgets.add(LineWidget(width: 0.5, height: 45.h));
    //   widgets.add(lookReport('修改标签', themeColor, btnWidth, id));
    // }
    for (int i = 0; i < btns.length; i ++) {
      if (btns[i] == '查看报告') {
        widgets.add(lookReport('查看报告', F2TextColor, btnWidth, id));
      } else if (btns[i] == '开始分期') {
        widgets.add(lookReport('开始分期', themeColor, btnWidth, id));
      } else if (btns[i] == '重新分期') {
        widgets.add(lookReport('重新分期', themeColor, btnWidth, id));
      } else if (btns[i] == '修改标签') {
        widgets.add(lookReport('修改标签', themeColor, btnWidth, id));
      }
      if (btns.length > 1 && i < btns.length - 1) {
        widgets.add(LineWidget(width: 1.w, height: 35.h, color: const Color(0xFFF8F9FB),));
      }
    }

    entity.data!.data![id].btnCount = buttonsCount;

    return widgets;
  }

  Widget lookReport(String text, Color color, double btnWidth, int id) {
    return InkWell(
      onTap: (){
        if (text == '开始分期') {
          isPop = true;
          NavigatorUtil.push(context, DataStagePage(id: entity.data!.data![id].id!,));
        } else if (text == '重新分期') {
          entry = OverlayEntry(builder: (ctx){
            isPop = true;
            return CommonAlert(title: '重新分期', msg: '重新分期后生成的报告将销毁，是否继续重新分期？', callback: (idx){
              if (idx == 1) {
                LogUtils.log('data id=${entity.data!.data![id].id!}');
                NavigatorUtil.push(context, DataStagePage(id: entity.data!.data![id].id!,));
              }
            }, entry: entry!);
          });
          Overlay.of(context).insert(entry!);
        } else if (text == '查看报告') {
          NavigatorUtil.push(context, PdfProviderPage(reportId: entity.data!.data![id].id!,));
        } else if (text == '修改标签') {
          entry = OverlayEntry(builder: (ctx) {
            List<PatientAllLabelData>? labelData = patientLabelModel!.data;
            if (labelData != null && labelData.isNotEmpty) {
              for (int i = 0; i < labelData!.length; i ++) {
                labelData[i].isChecked = false;
              }
              List<
                  AcquisitionAcquisitionLabelList>? patientShopLabelList = entity.data!.data![id].labelList;
              if (patientShopLabelList != null &&
                  patientShopLabelList.isNotEmpty) {
                for (int i = 0; i <
                    labelData!.length; i ++) {
                  for (int j = 0; j <
                      patientShopLabelList!.length; j ++) {
                    String label = entity.data!.data![id].labelList![j].name!;
                    if (labelData[i].name == label) {
                      labelData[i].isChecked = true;
                    }
                  }
                }
              }
            }
            return EditFlagAlert(title: '修改采集标签', entry: entry!, flagModels: patientLabelModel!.data!, actionCallback: (List<PatientAllLabelData> labelList){
              if (labelList.isEmpty){
                return;
              }
              List<String> list = [];
              List<AcquisitionAcquisitionLabelList> refreshLabel = [];
              for(int i = 0; i < labelList.length; i ++) {
                PatientAllLabelData data = labelList[i];
                if (data.isChecked) {
                  Map<String, String> m = <String, String>{};
                  m['id'] = data.id!;
                  m['name'] = data.name!;
                  m['colour'] = data.colour!;
                  AcquisitionAcquisitionLabelList label = AcquisitionAcquisitionLabelList();
                  label.id = data.id!;
                  list.add(data.id!);

                  label.id = data.id!;
                  label.name = data.name!;
                  label.colour = data.colour!;
                  refreshLabel.add(label);
                }
              }

              LogUtils.log('id=$id');
              NetBusiness().reportAddLabel(entity.data!.data![id].id!, list).then((value) {
                if (value) {
                  // ///重新查询患者详情，以拿到更新后的患者标签
                  // widget.labelList!.clear();
                  // for (int i = 0; i < list.length; i ++) {
                  //   Map<String, String> m = list[i];
                  //   AcquisitionAcquisitionLabelList label = AcquisitionAcquisitionLabelList();
                  //   label.colour = m['colour'];
                  //   label.id = m['id'];
                  //   label.name = m['name'];
                  //   widget.labelList!.add(label);
                  // }
                  // setState(() {
                  //   _getFlagWidget();
                  // });
                  // globalEventBus.fire(EventBufRefreshModel());
                  entity.data!.data![id].labelList = refreshLabel;
                  setState(() {
                    entity.data!.data;
                  });
                }
              });
            });
          }
          );
          Overlay.of(context).insert(entry!);
        }
      },
      child: _getButton(text, color, btnWidth, id)
    );
  }

  Widget _getButton(String text, Color color, double btnWidth, id) {
    return Container(
      alignment: Alignment.center,
      width: btnWidth,
      height: 40.h,
      child: Text(
        text,
        style: TextStyle(fontSize: 13, color: color, fontWeight: FontWeight.w600),
      ),
    );
  }
}
